package com.docMan.filter;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.InterceptorRef;

import com.docMan.service.TcroleService;
import com.docMan.utils.FinalConfig;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class AuthorityInterceptor extends AbstractInterceptor {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 471031967657385275L;
	private TcroleService tcroleService;
	@Resource(name="tcroleService")
	public void setTcroleService(TcroleService tcroleService) {
		this.tcroleService = tcroleService;
	}
	
	@SuppressWarnings("unused")
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		String url=ServletActionContext.getRequest().getRequestURL().toString()+"?"+ServletActionContext.getRequest().getQueryString();
		System.out.println("开始struts2的权限拦截"+url+ServletActionContext.getRequest().getSession().getId());
		String actionName = invocation.getProxy().getActionName();
		ActionContext ctx=invocation.getInvocationContext();
		Map<String, Object> session=ctx.getSession();
		ctx.getSession().put(FinalConfig.SESSION_HUMAN_IP, ServletActionContext.getRequest().getRemoteAddr());
		Integer requestHumanid=(Integer) ServletActionContext.getRequest().getAttribute(FinalConfig.SESSION_HUMANID);
		Integer humanid=(Integer) session.get(FinalConfig.SESSION_HUMANID);
		boolean isValid=ServletActionContext.getRequest().isRequestedSessionIdValid();
		session.put(FinalConfig.URL, url);
		if (url.indexOf("login.action") != -1
				|| url.indexOf("logout.action") != -1||url.indexOf("loginView.action") != -1) {
			String redirectUrl=(String) session.get(FinalConfig.REDIRECT_URL);
			if(redirectUrl!=null&&!redirectUrl.contains("login")){
				session.put(FinalConfig.IS_REDIRECT, true);
			}else{
				session.put(FinalConfig.IS_REDIRECT, false);
			}
			return invocation.invoke();
		}
		if(session.get(FinalConfig.SESSION_HUMANID)==null){
			//记录重定向的url
			if(!url.contains("login.action")&&!url.contains("loginView.action")){
				session.put(FinalConfig.REDIRECT_URL, url);
				session.put(FinalConfig.IS_REDIRECT, true);
			}
			return "login";
		}
		ctx.getSession().put("sessionId", ServletActionContext.getRequest().getSession().getId()+session.get(FinalConfig.SESSION_HUMANNAME));
		return invocation.invoke();
	}
	
}
